import MessageEvent from "../events/MessageEvent"
import cjs=createjs
import createjs from "createjs-ts"
export default class MessageController {
    private dispatcher=new cjs.EventDispatcher()
    /**
     * 发送消息
     * @param type 消息类型
     * @param data 数据
     */
    send(type:string,data?:any):void{
        const evt=new MessageEvent(type,false,false,data)
        this.dispatcher.dispatchEvent(evt)
    }
    dispatchEvent(typeorevt:string|cjs.Event,bubbles=false,cancelable=false):void{
        if(typeorevt instanceof cjs.Event){
            this.dispatcher.dispatchEvent(typeorevt)
        }else{
            this.dispatcher.dispatchEvent(new cjs.Event(typeorevt,bubbles,cancelable))
        }
    }
    /**
     * 接收消息，一次性
     * @param type 消息类型
     * @param listener 监听器
     * @param scope this指向
     */
    once(type:string,listener:()=>any,scope?:any):void{
        this.dispatcher.on(type,listener,scope,true)
    }
    /**
     * 接收消息
     * @param type 消息类型
     * @param listener 监听器
     * @param scope this指向
     */
    on(type:string,listener:(e:cjs.Event)=>void,scope?:any):any{
        return this.dispatcher.on(type,listener,scope,false)
    }
    /**
     * 移除消息监听
     * @param type 消息类型
     * @param listener 监听器
     */
    off(type:string,listener:()=>any):void{
        this.dispatcher.off(type,listener)
    }
}